package com.chensi.admin.web.controller;

import com.chensi.admin.web.common.Constants;
import com.chensi.admin.web.controller.api.SysLoginApi;
import com.chensi.admin.web.exception.BaseException;
import com.chensi.admin.web.service.SysLoginService;
import com.chensi.admin.web.common.JsonResult;
import com.chensi.admin.web.dto.SysLoginDTO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: si.chen
 * @Date: 2019/6/19 14:39
 */
@RestController
public class SysLoginController extends BaseController implements SysLoginApi {

    private final SysLoginService sysLoginService;

    @Autowired
    public SysLoginController(SysLoginService sysLoginService) {
        this.sysLoginService = sysLoginService;
    }

    @Override
    @PostMapping("login")
    public ResponseEntity<JsonResult> login(@Validated({Constants.Login.class})
                                            @RequestBody SysLoginDTO sysLoginDTO) throws BaseException {
        return ResponseEntity.ok(JsonResult.ok(sysLoginService.login(sysLoginDTO)));
    }

    @Override
    @PostMapping("logout")
    public ResponseEntity<JsonResult> logout() throws BaseException {
        sysLoginService.logout(getUserId());
        return ResponseEntity.ok(JsonResult.ok());
    }

    @Override
    @PostMapping("updatePassword")
    public ResponseEntity<JsonResult> updatePassword(@Validated({Constants.Password.class})
                                                     @RequestBody SysLoginDTO sysLoginDTO) throws BaseException {
        sysLoginDTO.setUserId(getUserId());
        sysLoginService.updatePassword(sysLoginDTO);
        return ResponseEntity.ok(JsonResult.ok());
    }

    @PostMapping("current")
    @RequiresPermissions(value = {"sys:user:update1"})
    public ResponseEntity<JsonResult> current() throws BaseException {
        return ResponseEntity.ok(JsonResult.ok(getUser().getUsername()));
    }
}
